package com.doctor.ui.consulting;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.doctor.adapter.ShowImageAdapter;
import com.doctor.bean.ContactsBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FileHelper;
import com.doctor.comm.ImageHelper;
import com.doctor.comm.DialogHelper.MultipleDialogCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.ImageHelper.TakePictureCallback;
import com.doctor.comm.LoadingTip;
import com.doctor.database.DbOperator;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.DragImageActivity;
import com.doctor.ui.R;
import com.doctor.view.NoScrollGridView;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class SendSmsFrag extends BaseFragment{

	/**
	 * 发送短信
	 */
	
	private Context context;
	private EditText smsReceiver,title,content;   //标题、内容
	private TextView addReceiverBtn,uploadBtn,takePhotoBtn;    //上传、拍照
	private LinearLayout sendBtn,cancelBtn;     //保存、取消
	private ReceiverCast receiverCast;
	//显示图片之用
	private NoScrollGridView gridView;
	private ShowImageAdapter adapter;
	private Uri imageUri;
	private List<String> beanList;	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.context=getActivity();
		
		View view=inflater.inflate(R.layout.send_sms, container, false);
		initiaView(view);
		getData();
		
		return view;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		//注册短信发送状态广播
		super.onResume();
		if (receiverCast==null) {
			receiverCast=new ReceiverCast();
		}
		IntentFilter filter=new IntentFilter();
		filter.addAction("SENT_SMS_ACTION");
		context.registerReceiver(receiverCast, filter);
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		//取消广播
		super.onPause();
		if (receiverCast!=null) {
			try {
				context.unregisterReceiver(receiverCast);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	//初始化控件
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		title=(EditText) view.findViewById(R.id.title);
		content=(EditText) view.findViewById(R.id.content);
		
		ImageListener imageListener=new ImageListener();
		uploadBtn=(TextView) view.findViewById(R.id.uploadBtn);
		uploadBtn.setOnClickListener(imageListener);
		
		takePhotoBtn=(TextView) view.findViewById(R.id.takePhotoBtn);
		takePhotoBtn.setOnClickListener(imageListener);
		
		sendBtn=(LinearLayout) view.findViewById(R.id.sendBtn);		
		sendBtn.setOnClickListener(new OnClickListener() {		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<String> images=adapter.getPics();
				if (images.size()>0) {
					ArrayList<Uri> uris = new ArrayList<Uri>(images.size());
					for (String pic : images) {
						uris.add(Uri.fromFile(new File(pic)));
					}
					//发送彩信
					sendSmsInfo(false, uris);
				} else {
					//发送文字短信
					sendSmsInfo(true,null);
				}
			}
		});
		
		cancelBtn=(LinearLayout) view.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getActivity().getSupportFragmentManager().popBackStack();
			}
		});
		
		smsReceiver=(EditText) view.findViewById(R.id.smsReceiver);
		addReceiverBtn=(TextView) view.findViewById(R.id.addReceiverBtn);
		
		addReceiverBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				List<ContactsBean> beanList=DbOperator.getInstance(context).selectDoctorContacts(1);
				if (beanList!=null && beanList.size()>0) {
					DialogHelper.showMultipleDialog(context, null, beanList,new MultipleDialogCallback() {					
						@Override
						public void onConfirmClicked(Map<Integer, ContactsBean> map) {
							// TODO Auto-generated method stub
							if (map.size()>0) {
								StringBuilder builder=new StringBuilder();
								builder.append(smsReceiver.getText().toString());
								for (int id : map.keySet()) {
									builder.append(map.get(id).getContacts()+";");
								}
								smsReceiver.setText(builder.toString());
							}
						}
					});
				} else {
					Toast.makeText(context, "没有可供选择的联系人！", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		gridView=(NoScrollGridView) view.findViewById(R.id.gridView);
		beanList=new ArrayList<String>();
		adapter=new ShowImageAdapter(context, beanList);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				Uri uri=(Uri) arg1.getTag(R.id.bean_tag);
				Intent intent=new Intent(getActivity(),DragImageActivity.class);
				intent.putExtra(getResources().getString(R.string.uri), uri.toString());
				startActivity(intent);
				
			}
		});
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, final View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {	
					@Override
					public void onClicked(int position) {
						// TODO Auto-generated method stub
						if (position==1) {
							String pic=(String) arg1.getTag(R.id.bean_tag);
							adapter.removeBean(pic);
						}
					}
				});
				return false;
			}
		});
	}
	
	@Override
	protected void getData() {
		// TODO Auto-generated method stub
		String tel=getArguments().getString("tel");
		smsReceiver.setText(tel+";");
	}
	
	private void sendSmsInfo(boolean isTex, ArrayList<Uri> images){
		String smsReceiver_txt=smsReceiver.getText().toString().trim();
		if (smsReceiver_txt==null || "".equals(smsReceiver_txt)) {
			Toast.makeText(context, "请填写收件人！", Toast.LENGTH_SHORT).show();
			return;
		}
		String[] receiverPeople=smsReceiver_txt.split(";");
		
		String content_txt=content.getText().toString().trim();
		
		if (isTex) {
			//文字短信
			if (content_txt==null || "".equals(content_txt)) {
				Toast.makeText(context, "请填写短信内容！", Toast.LENGTH_SHORT).show();
				return;
			}		
			
			LoadingTip.showDialog(context, "正在发送短信...");
			SmsManager smsManager=SmsManager.getDefault();
			//切分短信，一条短信最多70个字
			List<String> messages=smsManager.divideMessage(content_txt);
			if (isTex) {
				Intent sendIntent=new Intent("SENT_SMS_ACTION");
				PendingIntent sendPi=PendingIntent.getBroadcast(context, 0, sendIntent, 0);
				//群发短信
				for (String people : receiverPeople) {
					for (String message : messages) {
						smsManager.sendTextMessage(people, null, message, sendPi, null);
						ContentValues values=new ContentValues();
						values.put("date", System.currentTimeMillis());
						values.put("read", 0);
						//type1表示接收2表示发出
						values.put("type", 2);
						values.put("address", people);
						values.put("body", message);
						//写入短信库
						context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
					}
				}
			}
		} else {
			//彩信，调用系统界面
			Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
			//有些android版本找不到ComposeMessageActivity，所以改用分享组件的方式来调用彩信
//		    intent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
			
		    String title_txt=title.getText().toString().trim();
		    if (title_txt!=null && !"".equals(title_txt)) {
		    	intent.putExtra("subject", title_txt);
			}
		    
		    if (content_txt!=null && !"".equals(content_txt)) {
		    	intent.putExtra("sms_body", content_txt);
			}		    
		    intent.putExtra("address", smsReceiver_txt);		    
		    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, images);
		    intent.setType("image/*");
		    startActivityForResult(intent, 0);
		}
	}
	
	//用于接收短信发送之后状态的广播
	private class ReceiverCast extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			LoadingTip.hideDialog();
			if (getResultCode()==Activity.RESULT_OK) {
				Toast.makeText(context, "短信发送成功！", Toast.LENGTH_SHORT).show();
				smsReceiver.setText("");
				title.setText("");
				content.setText("");
			} else {
				Toast.makeText(context, "短信发送失败！", Toast.LENGTH_SHORT).show();
			}
		}
		
	}
	
	
	/**
	 * 上传和拍照
	 * @author
	 *
	 */
	private class ImageListener implements OnClickListener{
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			if (arg0==uploadBtn) {
				ImageHelper.selectPicture(SendSmsFrag.this, ConstConfig.CHOOSE_PICTURE,null);
			} else if (arg0==takePhotoBtn) {
				ImageHelper.selectPicture(SendSmsFrag.this, ConstConfig.TAKE_PICTURE,new TakePictureCallback() {					
					@Override
					public void onGetImageName(Uri imageUri) {
						// TODO Auto-generated method stub
						SendSmsFrag.this.imageUri=imageUri;
					}
				});
			}
		}
	}
	
	
	//选择图片或拍照完成后返回图片路径
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//-1=RESULT_OK
		if (resultCode==-1) {
			Uri imageUri = null;	
			switch (requestCode) {
			case ConstConfig.CHOOSE_PICTURE:
				if (data!=null) {
					imageUri=data.getData();
				}
				break;
				
			case ConstConfig.TAKE_PICTURE:
				imageUri=SendSmsFrag.this.imageUri;
				SendSmsFrag.this.imageUri=null;
				break;
				
			default:
				break;
			}
			if (imageUri!=null) {
				String picPath = FileHelper.uri2Path(context, imageUri);
				if (picPath != null && picPath.length() > 0) {
					adapter.addBean(picPath);
					adapter.notifyDataSetChanged();
				}
			}
		} 
	}
	
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		if (adapter != null) {
			adapter.clear();
		}
	}
	
}
